<template>
	<scroll-view scroll-y="true" :scroll-top="scrollTop" @scrolltolower="loadMore" @scrolltoupper="refresh"
		scroll-with-animation="true" class="scroll-view">
		<view class="body" :class="{'no-scroll': isMask}">
			<view v-if="isMask" class="mask" @click="onMask"></view>
			<view class="bg">
				<image :src="$IMAGE_BASE_URL2 + '/yangcan/bg.png'"
					style="width: 100%; height:1377rpx;margin: auto; display: block;"></image>
			</view>
			<view class="home">
				你好，{{nickName?nickName:'游客'}}
			</view>
			<view class="device top">
				<view class="device-nav">
					<view class="active">氧舱</view>
					<view @click="jump('pages/tableLamp/index')">星梦云康</view>
				</view>
				<view class="scan-icon" @click="onScanDeviceCode">
					<image src="@/img/yangcan/ic_scan.png"></image>
				</view>
			</view>
			<view style="margin-top: 10rpx; top">
				<WeekList ref="weekListRef" :isClick="true" @click="toReservation" />
			</view>
			<view class="tongji top" @click="jump('pages/chart/oxygen/statistics',oxSta)">
				<view class="title">数据统计</view>
				<view class="content">
					<view class="week">
						<view class="qk">周完成情况</view>
						<view class="xq">查看详情></view>
					</view>
				</view>
				<view class="xq2 top">
					<view class="left">
						<view style="border-radius: 26rpx 0 0 26rpx;" :class="oxSta.weekCount > 0 ? 'active' : ''">
							<image v-if="oxSta.weekCount>0" :src="$IMAGE_BASE_URL2 + '/yangcan/gou.png'"
								style="width: 28rpx; height:20rpx;margin: auto; display: block;margin-top: 16rpx;">
							</image>
						</view>
						<view :class="oxSta.weekCount > 1 ? 'active' : ''">
							<image v-if="oxSta.weekCount>1" :src="$IMAGE_BASE_URL2 + '/yangcan/gou.png'"
								style="width: 28rpx; height:20rpx;margin: auto; display: block;margin-top: 16rpx;">
							</image>
						</view>
						<view style="border-radius:0 26rpx 26rpx 0;" :class="oxSta.weekCount > 2 ? 'active' : ''">
							<image v-if="oxSta.weekCount>2" :src="$IMAGE_BASE_URL2 + '/yangcan/gou.png'"
								style="width: 28rpx; height:20rpx;margin: auto; display: block;margin-top: 16rpx;">
							</image>
						</view>
					</view>
					<view class="right">
						<text style="color: #888888;">{{oxSta.weekCount?oxSta.weekCount:'--'}}</text>
						<text style="color: #fe7610;">/3</text>
						<image :src="$IMAGE_BASE_URL2 + '/yangcan/jiayou.png'"
							style="width: 94rpx; height:52rpx;margin: auto; display: block; margin-left: 16rpx;">
						</image>
					</view>
				</view>
				<view class="zhinan top">
					<image :src="$IMAGE_BASE_URL2 + '/yangcan/zhinan.png'"
						style="width: 31rpx; height:31rpx;display: block; margin:0 16rpx;"></image>
					氧护指南：每周规律吸氧 3 次以上，能深层焕活身体细胞 。
				</view>
				<view class="xq2 top">
					<view class="tj">
						<view class="name">吸氧次数</view>
						<view class="num">{{oxSta.weekCount?oxSta.weekCount:'--'}}<text class="name">次</text>
							<u-icon v-if="oxSta.weekCount > oxSta.lastWeekCount" name="arrow-upward" color="#fe7610"
								size="22"></u-icon>
							<u-icon v-else name="arrow-downward" color="#fe7610" size="22"></u-icon>
						</view>
					</view>
					<view class="tj">
						<view class="name">吸氧时长</view>
						<view class="num">{{oxSta.weekTime?(oxSta.weekTime/60).toFixed(2):'--'}}<text
								class="name">小时</text></view>
					</view>
					<view class="tj">
						<view class="name">上周吸氧次数</view>
						<view class="num">{{oxSta.lastWeekCount?oxSta.lastWeekCount:'--'}}<text class="name">次</text>
						</view>
					</view>
				</view>
			</view>
			<view class="zxxy top" v-if="deviceInfo[2007].value != 0 && deviceInfo[3000].value != 0"
				@click="jump('pages/oxygen/realTime',{deviceList:JSON.stringify(deviceList)})">
				正在吸氧<image :src="$IMAGE_BASE_URL2 + '/yangcan/zxxy.png'"
					style="width: 43rpx; height:24rpx;display: block; margin:24rpx 16rpx;"></image>
				<view class="right">查看实时数据<image :src="$IMAGE_BASE_URL2 + '/yangcan/jt2.png'"
						style="width: 37rpx; height:21rpx;display: block; margin:26rpx 16rpx;"></image>
				</view>
			</view>
			<view class="latest-data top" style="margin-top: 20rpx;"
				@click="jump('pages/chart/oxygen/details',{item:items[0]?JSON.stringify(item[0]):'',deviceList:JSON.stringify(deviceList)})">
				<view style="display: flex;">
					<view class="title">最新一次数据(30天)</view>
					<view class="data">{{items[0]?$u.timeFormat(items[0].startTime, 'yyyy-mm-dd hh:MM:ss'):'--'}}</view>
				</view>
				<view style="display: flex;flex-wrap: wrap">
					<view class="vital-signs">
						<view class="name">
							<image src="@/img/yangcan/xl.png"
								style="width: 32rpx; height:26rpx;display: block;margin-right: 10rpx; margin-top: 6rpx;">
							</image>心率
						</view>
						<view class="num">{{items[0]?items[0].avgHr:'--'}}<text class="unit">bpm</text></view>
					</view>
					<view class="vital-signs">
						<view class="name">
							<image src="@/img/yangcan/hx.png"
								style="width: 33rpx; height:33rpx;display: block;margin-right: 10rpx;margin-top: 4rpx;">
							</image>呼吸
						</view>
						<view class="num">{{items[0]?items[0].avgRr:'--'}}<text class="unit">次/分</text></view>
					</view>
					<!-- 舱内数据 -->
					<view class="vital-signs">
						<view class="name">
							<image src="@/img/yangcan/cnyl.png"
								style="width: 40rpx; height:40rpx;display: block;margin-right: 10rpx;margin-top: 0rpx;">
							</image>舱内压力
						</view>
						<view class="num">{{items[0]?items[0].avgPressure:'--'}}<text class="unit">kpa</text></view>
					</view>
					<view class="vital-signs">
						<view class="name">
							<image src="@/img/yangcan/sj.png"
								style="width: 38rpx; height:38rpx;display: block;margin-right: 10rpx;margin-top: 1rpx;">
							</image>时间
						</view>
						<view class="num">{{items[0]?items[0].totalTime:'--'}}<text class="unit">分钟</text></view>
					</view>
				</view>
				<!-- 健康状态 -->
				<view class="health-status">
					<view>
						<text class="name">疲劳程度</text>
						<text class="jieguo">{{interval.arrhythmia}}</text>
					</view>
					<view>
						<text class="name">心率不齐</text>
						<text class="jieguo">{{interval.fatigue}}</text>
					</view>
				</view>
			</view>
			<view class="neirong">
				<view class="title">
					<text style="padding-left: 0rpx;font-size: 36rpx;line-height: 54rpx;font-weight: bold;">吸氧记录</text>
					<view class="chooseMonth">
						<picker mode="date" :value="$u.timeFormat(endTime, 'yyyy-mm-dd')" @change="bindDateChange"
							fields="month">
							{{$u.timeFormat(endTime, 'yyyy-mm')}}
							<u-icon style="margin-left: 10rpx;" name="arrow-down" color="#a7a7a7" size="28"></u-icon>
						</picker>
					</view>
				</view>

				<view class="info">
					<view class="container">
						<!-- 下拉刷新容器 -->
						<!-- 刷新状态提示 -->
						<view v-if="refreshing" class="refreshing">正在刷新...</view>
						<!-- 列表项 -->
						<!-- <view class="list" >
								<view class="fl">{{$u.timeFormat(item.time*1, 'yyyy-mm-dd hh:MM:ss')}}</view>
								<view class="fr">
									<text v-if='item.value < alarm.down' class='red'>{{item.value}}</text>
									<text v-if='item.value > alarm.down'>{{item.value}}</text>
								</view>
							</view> -->

						<view class="list" v-if='items.length > 0' v-for="(item, index) in items" :key="index">
							<view class="jilu"
								@click="jump('pages/chart/oxygen/details',{item:JSON.stringify(item),deviceList:JSON.stringify(deviceList)})">
								<view class="yuan"></view>
								<view class="title">
									<view>{{$u.timeFormat(item.startTime, 'yyyy-mm-dd')}}</view>
									<view class="time">
										吸氧时间：{{$u.timeFormat(item.startTime, 'hh:MM')}}-{{$u.timeFormat(item.endTime, 'hh:MM')}}
									</view>
								</view>
								<view class="content">
									<view class="lable">
										<view class="leibie">心率</view>
										<view class="num">{{item.avgHr}}</view>
										<view class="danwei">bmp</view>
									</view>
									<view class="lable">
										<view class="leibie">呼吸</view>
										<view class="num">{{item.avgRr}}</view>
										<view class="danwei">次/分</view>
									</view>
									<view class="lable">
										<view class="leibie">压力</view>
										<view class="num">{{item.avgPressure}}</view>
										<view class="danwei">kpa</view>
									</view>
									<view class="lable">
										<view class="leibie">时长</view>
										<view class="num">{{item.totalTime}}</view>
										<view class="danwei">分</view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="data-null">
							<image src="/img/yangcan/noData.png"
								style="width: 36rpx;height: 36rpx;padding-right: 10rpx;"></image>暂无数据
						</view>
						<!-- 加载状态提示 -->
						<view v-if="loading" class="loading">加载中...</view>
						<!-- 无更多数据提示 -->
						<view v-if="noMoreData" class="no-more-data">没有更多数据</view>
					</view>
				</view>
			</view>
			<view style="height: 180rpx;"></view>
			<Tabbar :selected="1" />
			<u-popup v-model="showTIshi" mode="center" border-radius="15" width="80%" z-index="888">
				<view class="popup"
					style="background: linear-gradient(180deg,#ff720a, #ffffff); height: 210rpx;text-align: center;">
					<image src="@/img/new/tishi.png"
						style="width: 96rpx; height: 82rpx; display: block;padding: 45rpx 0 25rpx 0 ; margin: auto;">
					</image>
					暂无数据
				</view>
			</u-popup>
		</view>
	</scroll-view>
</template>
<script>
	import WeekList from '@/components/calendar/week-list.vue';
	import LunarCalendar from 'lunar-calendar'
	import UserService from '@/service/UserService.js'
	import CacheConfig from "../../config/CacheConfig";
	import * as UserApi from '@/api/user';
	import * as AddressApi from '@/api/address'
	import {
		device,
		home,
		homeList,
		homeMembers,
		getalarm,
		postalarm
	} from "../../api/login/index.js";
	import {
		getoxlist,
		getoxTimes
	} from "../../api/ox.js";
	import {
		getPropert,
		propertLast,
		getScenenotify,
		historyPropert,
	} from "../../api/device/index.js";
	import StorageUtils from "../../utils/StorageUtils";
	import SimDevice from '../../service/mqtt/sim/SimDevice.js';
	import {
		DeviceBasicData
	} from '../../service/mqtt/DeviceConfig.js';
	import {
		checkBloodSugarStatus
	} from '@/common/alarm/BG.js'

	export default {
		data() {
			return {
				weekList: [],
				startTime: Date.parse(new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000)),
				endTime: Date.parse(new Date()),
				interval: {
					minMinValue: 0,
					maxMaxValue: 0,
					arrhythmia: '--',
					fatigue: '--',
				},
				showTIshi: false,
				oxSta: {
					weekCount: 0
				}, //吸氧统计
				items: [], // 列表数据
				refreshing: false, // 是否正在刷新
				loading: false, // 是否正在加载更多
				noMoreData: false, // 是否没有更多数据
				page: 0, // 当前页码
				scrollTop: 0, // 滚动条位置，用于重置滚动位置到顶部
				deviceInfo: {
					2007: {
						value: 0
					},
					3000: {
						value: 0
					}
				},
				nickName: '',
				isMask: false,
			};
		},
		components: {
			WeekList,
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		computed: {},
		onReady() {
			// this.getServerData();
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			// 当前页面参数
			this.options = options;
			const token = StorageUtils.get(CacheConfig.TOKEN_KEY);
			if (token) {
				this.login();
			}
		},
		onUnload() {},
		onShow() {
			// this.login();
			this.nickName = StorageUtils.get('USER_INFO_KEY').nickName
			// console.log(123123213213213213132);
			if (!!StorageUtils.get('ALARM') && !!StorageUtils.get('uuid')) {
				console.log('开始获取设备信息！');
				// this.getDevice(StorageUtils.get('uuid'))
				this.upInfo(StorageUtils.get('uuid'));
				// this.getAddressList()
			}
		},
		onHide() {
			if (this.mqttPing) {
				clearInterval(this.mqttPing);
				this.simDevice.close();
			}
			this.isMask = false;
			this.isAddView = false;
		},
		methods: {
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			bindDateChange: function(e) {
				let date = e.detail.value.split('-');
				// date[0], date[1], date[2] 年月日
				this.startTime = new Date(date[0] * 1, date[1] * 1 - 1, 1, 0, 0, 0, 0).getTime();
				this.endTime = new Date(date[0] * 1, date[1] * 1, 0, 23, 59, 59, 999).getTime();
				this.loadData(this.startTime, this.endTime, true)
			},

			//通过分数渐变
			getClassName() {
				let val = this.deviceInfo.report ? this.deviceInfo.report.value.sleepQualityScore : 100
				if (val >= 0 && val <= 59) {
					return 'bad jianbian';
				} else if (val >= 60 && val <= 89) {
					return 'general jianbian';
				} else if (val > 90) {
					return 'good jianbian';
				} else {
					return 'jianbian'; // 如果需要处理其他情况，可以返回默认类或空字符串
				}
			},
			//分数返回结果
			qualityText(val) {
				if (val >= 60 && val <= 89) {
					return '良好';
				} else if (val < 60) {
					return '差'; // 或者其他适当的文本
				} else {
					return '很好'; // 或者其他适当的文本
				}
			},
			onScanDeviceCode() {
				if (!this.$isLogin()) return;
				const that = this;
				this.$addDeviceService.scanCodeYangCang({
					yangcanBind: () => {
						console.log("绑定成功");
						that.upInfo(StorageUtils.get('uuid'));
					}
				});
			},
			toReservation() {
				if (!this.$isLogin()) return;
				this.jump('pages/oxygen/reservation');
			},
			onMask() {
				this.isMask = false;
				this.isAddView = false;
			},
			onShowAddView() {
				if (this.isManager) {
					this.isMask = true;
					this.isAddView = true;
				} else {
					this.onAddDevice();
				}
			},
			onAddDevice() {
				if (!this.$isLogin()) return;
				this.$addDeviceService.scanCode();
			},
			onAddMember() {
				console.log("添加成员");
				if (!this.$isLogin()) return;
				this.jump('pages/mine/invite');
			},
			jump(url, data) {
				if (!this.$isLogin()) return;
				// console.log("jump", data);
				if (url == 'pages/tableLamp/tableLamp') {
					if (data.iotDeviceId == undefined) {
						this.showTIshi = true;
						return false;
					}

				}
				if (url == 'pages/chart/HealthReport/index') {
					if (data) {
						StorageUtils.save('ReportData', data.time);
					} else {
						StorageUtils.remove('ReportData');
					}
				}
				if (url == 'pages/chart/oxygen/details') {
					if (data.item == '') {
						this.showTIshi = true;
						return false
					}
				}
				if (this.mqttPing) {
					clearInterval(this.mqttPing);
					this.simDevice.close();
				}
				this.$navTo(url, {
					...data
				}, )
			},
			// showAlarm(obj) {
			// 	getalarm({
			// 		alarmType: obj
			// 	}).then(res => {
			// 		if (obj == 'BP') {
			// 			this.BPalarm = JSON.parse(res.obj.alarmContent)
			// 		}
			// 		this.showBPalarm = true
			// 	})
			// },
			mqtt(device) {
				let deviceBasicData = new DeviceBasicData('', '', undefined);
				this.simDevice = new SimDevice();
				let url = '47.97.72.174:1887';
				// let url = '123.60.177.231:1887';
				deviceBasicData.username = '1559108322@qq.com';
				deviceBasicData.password = '123456';
				deviceBasicData.addr = url;
				let that = this;
				this.simDevice.clientDataListener = {
					onHandle: (topic, msg) => {
						msg = msg.replace(/'/g, '"');
						if (JSON.parse(msg).method === 'thing.service.property.post') {
							let info = JSON.parse(msg);
							let item = info.params;
							let data = {}
							if (item == undefined) {
								return false;
							}
							if ('Result' in item) {
								let val = checkBloodSugarStatus(item.Result, JSON.parse(StorageUtils.get('ALARM'))
									.BG);
								item.Result.bloodSugarLevel = val.bloodSugarLevel
							}
							if ('report' in item) {
								data.value = JSON.parse(item.value.replace(/-/g, ""))
								data.report = item;
							}
							this.deviceInfo = {
								...this.deviceInfo,
								...item,
								...data
							}
							// console.log(that.deviceInfo);
							// console.log(this.deviceInfo[2007].value,this.deviceInfo[3000].value);
						}
					},
					onSetProperty: (requestPayload) => {
						let params = requestPayload.params;
					},
					onConnect(success) {
						console.log('连接服务器:' + success);
						if (success) {
							device.map(val => {
								if (val.deviceType == "LIGHT") {
									that.LIGHT = val
								}
								that.simDevice.subscribe(val.productKey, val.deviceName)
							})
							// console.log(213231231232132132132132132121321);
							// that.simDevice.subscribe('o86vNHeJpJW', '5FA2516004966852')

							that.mqttPing = setInterval(() => {
								that.simDevice.ping()
							}, 30000);

						}
					},
					onClose() {
						console.log('连接关闭');
					}
				};
				this.simDevice.init(deviceBasicData);
				this.simDevice.connectServer();
			},
			async login() {
				await UserService.wxLogin();
				if (!StorageUtils.get('uuid')) {
					let uuid = UserService.userInfo.uuid;
					// console.log("uuid", uuid);
					// uuid = 100143
					await StorageUtils.save('uuid', uuid);
					// setCartTabBadge();
					this.nickName = StorageUtils.get('USER_INFO_KEY').nickName
					this.upInfo(uuid);
				} else {
					this.upInfo(StorageUtils.get('uuid'));
				}
				this.$refs.weekListRef.initData();
			},
			getOXTimes() {
				getoxTimes({}).then(res => {
					this.oxSta = res.obj
				}).catch(error => {
					uni.showToast({
						title: '加载失败',
						icon: 'none',
					});
				});
			},
			loadData(startTime, endTime, refresh = false) {
				let app = this;
				if (refresh) {
					this.noMoreData = false
				}
				if (this.refreshing || this.loading || this.noMoreData) return;
				if (!StorageUtils.get('USER_INFO_KEY')) {
					return false
				}
				let isRefresh = refresh;
				if (refresh) {
					this.refreshing = true;
					this.page = 1; // 刷新时重置页码为1
					this.items = []; // 清空列表数据
				} else {
					this.loading = true;
					this.page += 1; // 加载更多时页码加1
				}
				getoxlist({
					current: this.page,
					startTime: startTime ? startTime : this.startTime,
					endTime: endTime ? endTime : this.endTime,
					size: 20,
				}).then(res => {
					res = res.obj
					let data = res.records.map((val, index) => {
						if (index == 0) {
							app.gethistoryPropert(new Date(val.startTime.replace(/-/g, '/')).getTime(),
								new Date(val.endTime.replace(/-/g, '/')).getTime())
						}
						return {
							...val,
							avgPressure: (val.avgPressure * 1).toFixed(2),
							startTime: val.startTime.replace(/-/g, '/'),
							endTime: val.endTime.replace(/-/g, '/')
						}
					})
					if (data) {
						if (isRefresh) {
							this.items = data;
						} else {
							this.items = [...this.items, ...data];
						}
					}
					if (this.page > res.pages && res.pages >0) {
						this.noMoreData = true;
					}
					if (isRefresh) {
						this.refreshing = false;
						this.scrollTop = 0; // 刷新成功后重置滚动位置到顶部（如果需要）
					} else {
						this.loading = false;
					}
				}).catch(error => {
					console.log(error);
					if (isRefresh) {
						this.refreshing = false;
					} else {
						this.loading = false;
					}
					uni.showToast({
						title: '加载失败',
						icon: 'none',
					});
				});
			},
			// 下拉刷新
			refresh() {
				// this.loadData(true);
			},
			// 上拉加载更多
			loadMore() {
				if(items.length > 0){
					this.loadData();
				}
			},
			upInfo(uuid) {
				const now = new Date();
				let newdata = this.$u.timeFormat(now, 'mm-dd')
				const lunar = LunarCalendar.solarToLunar(now.getFullYear(), now.getMonth() + 1, now.getDate());
				const lunarDate = `${lunar.lunarMonth}月${lunar.lunarDay}日`;
				let that = this;
				if (StorageUtils.get('USER_INFO_KEY')) {
					this.loadData();
					this.getOXTimes();
				}
				getalarm({
					userId: uuid
				}).then(res => {
					const transformedData = {};
					let alarm = {}
					res.obj.forEach(item => {
						let alarmType = item.alarmType;
						let alarmContent = JSON.parse(item.alarmContent);
						alarm[alarmType] = alarmContent;
					});
					that.alarm = alarm
					StorageUtils.save('ALARM', JSON.stringify(this.alarm));
					StorageUtils.save('uuid', uuid);
					this.getDevice(uuid)
				}).catch(error => {});

			},
			gethistoryPropert(startTime, endTime) {
				historyPropert({
					startTime: startTime,
					endTime: endTime,
					current: 1,
					size: 10000,
					identifier: 'arrhythmia,fatigue'
				}).then(res => {
					// 创建一个对象来统计每个key下的value出现的次数
					const keyValueCount = {};
					// 遍历数组，统计每个key下的value出现的次数
					if (res.obj.records.length == 0) {
						return false;
					}
					res.obj.records.forEach(item => {
						const {
							key,
							value
						} = item;
						if (!keyValueCount[key]) {
							keyValueCount[key] = {};
						}
						if (keyValueCount[key][value]) {
							keyValueCount[key][value]++;
						} else {
							keyValueCount[key][value] = 1;
						}
					});
					// 找出每个key下出现次数最多的value
					const result = {};
					for (const key in keyValueCount) {
						let maxValue = null;
						let maxCount = 0;
						for (const value in keyValueCount[key]) {
							if (keyValueCount[key][value] > maxCount) {
								maxValue = value;
								maxCount = keyValueCount[key][value];
							}
						}
						result[key] = {
							value: maxValue,
							count: maxCount
						};
					}
					this.interval.arrhythmia = result.arrhythmia.value
					this.interval.fatigue = result.fatigue.value
				})
			},
			findNearestReminder(scenes) {
				const now = new Date();
				const currentDay = now.getDay();
				const currentHour = now.getHours();
				const currentMinute = now.getMinutes();

				let nearestScene = null;
				let nearestTimeDiff = Infinity;
				let nearestReminderTime = null;

				const dayMap = {
					"SUNDAY": 0,
					"MONDAY": 1,
					"TUESDAY": 2,
					"WEDNESDAY": 3,
					"THURSDAY": 4,
					"FRIDAY": 5,
					"SATURDAY": 6
				};

				scenes.forEach(scene => {
					if (scene.inUse) {
						const conditions = JSON.parse(scene.conditionJson);
						conditions.forEach(condition => {
							const {
								logicFrequency,
								hour,
								minute
							} = condition;
							logicFrequency.forEach(dayStr => {
								const day = dayMap[dayStr];
								let daysDiff = day - currentDay;
								if (daysDiff < 0) {
									daysDiff += 7;
								}
								let reminderTime = new Date(now.getFullYear(), now.getMonth(),
									now.getDate() + daysDiff, hour, minute);
								let timeDiff = reminderTime.getTime() - now.getTime();
								if (timeDiff < 0) {
									reminderTime = new Date(now.getFullYear(), now.getMonth(),
										now.getDate() + 7, hour, minute)
									timeDiff = reminderTime.getTime() - now.getTime();
								}
								if (timeDiff > 0 && timeDiff < nearestTimeDiff) {
									nearestTimeDiff = timeDiff;
									nearestScene = scene;
									nearestReminderTime = reminderTime;
								}
							});
						});
					}
				});
				if (nearestScene) {
					const lunar = LunarCalendar.solarToLunar(nearestReminderTime.getFullYear(), nearestReminderTime
						.getMonth() + 1, nearestReminderTime.getDate());
					const lunarDate = `${lunar.lunarMonth}月${lunar.lunarDay}日`;
					const formattedDate =
						`${String(nearestReminderTime.getMonth() + 1).padStart(2, '0')}-${String(nearestReminderTime.getDate()).padStart(2, '0')}`;
					const formattedTime =
						`${String(nearestReminderTime.getHours()).padStart(2, '0')}:${String(nearestReminderTime.getMinutes()).padStart(2, '0')}`;

					return {
						sceneName: nearestScene.sceneName,
						date: formattedDate,
						time: formattedTime,
						lunarDate: lunarDate
					};
				}

				return null;
			},
			getHomeMember(id, userId) {
				homeMembers({
					homeId: id
				}).then(res => {
					let uuid = StorageUtils.get('uuid');
					// let homeId=StorageUtils.get('homeId');
					res.obj.map((val, index) => {
						if (uuid == val.uuid) {
							res.obj[index].choose = 1;
							// this.currentUuid = res.obj[index].uuid;
						}
					})

					this.memberList = this.moveMatchedUuidToFirst(res.obj, userId);;
				})
			},
			moveMatchedUuidToFirst(arr, userId) {
				// 复制数组避免修改原数据
				const newArray = [...arr];
				// 查找匹配项的索引
				const index = newArray.findIndex(item => item.id === userId);

				if (index !== -1) {
					// 从原位置删除
					const matchedItem = newArray.splice(index, 1)[0];
					// 插入到数组开头
					newArray.unshift(matchedItem);
				}
				return newArray;
			},
			chooseMember(val) {
				this.deviceInfo = {
					connection: {
						value: 0
					},
				}
				this.LIGHT = {}
				this.memberList.map((val1, vindex) => {
					if (val1.uuid == val.uuid) {
						val1.choose = 1;
						this.upInfo(val.uuid);
						//当前选择的人
					} else {
						val1.choose = 0;
					}
				})
			},
			lastData() {
				propertLast().then(res => {
					const result = {};
					let obj = res.obj
					console.log(res);
					if (obj == null) return false;
					Object.keys(obj).forEach(key => {
						if (key == 'Result') {
							let val = checkBloodSugarStatus(obj[key], JSON.parse(StorageUtils.get('ALARM'))
								.BG);
							obj.Result.bloodSugarLevel = val.bloodSugarLevel
						}
						if (key == 'report') {
							obj.report.value = JSON.parse(obj.report.value.replace(/-/g, ""))
						}
						if (key == 'weight') {
							this.memberList.map((val, vindex) => {
								if (StorageUtils.get('uuid') == val.uuid && obj.weight.value * 1 !=
									val.weight) {
									const param = {
										weight: obj.weight.value * 1,
										id: val.id,
										appid: "wx9defdd2125f88fbb"
									};
									UserApi.updateUserInfoById(param).then(res => {
										console.log(1);
									}).catch(err => {
										// console.log("updateUserInfo error", err);
									});
								}
							})
						}
						result[key] = obj[key];
					});
					this.deviceInfo = {
						...this.deviceInfo,
						...result
					}
				});
			},
			getDevice(uuid) {
				device({
					uuid: uuid
				}).then(async res => {
					// this.lastData()
					try {
						// let types = this.allDeviceTypes;
						// let devices = res.obj;
						// for (let i = 0; i < types.length; i++) {
						// 	// 遍历第二个数组查找匹配项
						// 	for (let j = 0; j < devices.length; j++) {
						// 		// 检查deviceType是否包含typesArray中的type
						// 		// 注意：这里使用includes和toLowerCase进行简单的字符串匹配
						// 		// 如果deviceType包含type（不区分大小写），则更新nodevice属性
						// 		if (devices[j].deviceType.toLowerCase().includes(types[i].deviceType
						// 				.toLowerCase())) {
						// 			types[i].nodevice = false; // 设置为false表示已连接设备
						// 			types[i].iotDeviceId = devices[j].iotDeviceId;
						// 			// productKey deviceName
						// 			types[i].productKey = devices[j].productKey;
						// 			types[i].deviceName = devices[j].deviceName;
						// 			break; // 找到匹配项后退出内层循环
						// 		}
						// 	}
						// }
						// this.allDeviceTypes = types.sort((a, b) => a.nodevice ? 1 : -1);
						// this.allDeviceTypes = types
						this.deviceList = res.obj;
						if (this.mqttPing) {
							clearInterval(this.mqttPing);
							this.simDevice.close();
						}
						console.log('设备信息！' + JSON.stringify(res.obj));
						this.mqtt(res.obj)
					} catch (error) {
						console.error('Error fetching device info:', error);
					}
				}).catch(error => {
					console.error('Error fetching devices:', error);
				});
			},

		}
	};
</script>>



<style lang="scss">
	.scroll-view {
		height: 100vh;
	}

	.neirong {
		// background-color: #f2f2f2;
		padding: 20rpx 0 30rpx;
		// border-top: 20rpx solid #fff;
		margin-top: 20rpx;
		overflow: hidden;

		.title {
			padding-left: 20rpx;
		}

		.jilu {
			background-color: #fff;
			padding: 0 30rpx;
			position: relative;
			overflow: hidden;
			border-radius: 10rpx;
			margin-bottom: 20rpx;

			.yuan {
				width: 18rpx;
				height: 18rpx;
				border-radius: 50%;
				background-color: #ff8201;
				position: absolute;
				top: 30rpx;
				left: 15rpx;
			}

			.title {
				display: flex;
				border-bottom: 10px solid #f7f7f8;
				padding-left: 16rpx;

				.time {
					margin-left: auto;
					font-size: 24rpx;
				}
			}

			.content {
				display: flex;
				text-align: center;
				font-weight: bold;
				margin-bottom: 20rpx;

				.lable {
					width: 25%;
				}

				.leibie {
					font-size: 24rpx;
					line-height: 48rpx;
					color: #555555;
				}

				.danwei {
					font-size: 20rpx;
					line-height: 40rpx;
					color: #555555;
				}

				.num {
					font-size: 44rpx;
					line-height: 60rpx;
				}
			}
		}

		.title {
			font-size: 36rpx;
			line-height: 76rpx;
		}

		.chooseMonth {
			background-color: #fff;
			line-height: 64rpx;
			width: 200rpx;
			text-align: center;
			float: right;
			border-radius: 32rpx;
			font-size: 30rpx;
		}
	}

	.device {
		display: flex;
		margin-top: 20rpx;
		position: relative;
		z-index: 99;

		.device-nav {
			flex: 1;
			display: flex;
			align-items: center;
			margin-top: 20rpx;
			view {
				min-width: 120rpx;
				line-height: 60rpx;
				margin-right: 20rpx;
				font-size: 36rpx;
				text-align: center;
			}

			.active {
				background-color: #fb8020;
				color: #fff;
				border-radius: 18rpx;
			}
		}

		.scan-icon {
			width: 60rpx;
			height: 60rpx;
			border-radius: 60rpx;
			margin-top: 20rpx;
			background-color: #ffab4e;
			display: flex;
			align-items: center;
			justify-content: center;

			image {
				width: 30rpx;
				height: 30rpx;
			}
		}
	}

	.tongji {
		border-radius: 20rpx;
		position: relative;
		z-index: 99;
		margin-top: 15rpx;
		background-color: #fffdf9;
		overflow: hidden;

		.week {
			display: flex;
			line-height: 52rpx;
			padding: 0 20rpx;
			margin: 14rpx 0;

			.qk {
				color: #292626;
				font-size: 30rpx;
			}

			.xq {
				background-color: #fdead6;
				font-size: 24rpx;
				color: #fe710e;
				text-align: center;
				width: 150rpx;
				border-radius: 26rpx;
				margin-left: auto;
			}

		}

		.xq2 {
			display: flex;
			margin: 20rpx;

			.tj {
				text-align: center;
				width: 33.3%;
				background-color: #f5f5f7;
				padding: 20rpx;

				.name {
					font-size: 22rpx;
					color: #7b7b7b;
					line-height: 22rpx;
				}

				.num {
					font-size: 60rpx;
					line-height: 80rpx;
				}
			}

			.left {
				width: 75%;
				display: flex;

				view {
					background-color: #efe5da;
					width: 32%;
					margin: auto;
					height: 52rpx;
					line-height: 52rpx;
					text-align: center;
				}

				.active {
					background-color: #fe7610;
				}
			}

			.right {
				width: 25%;
				padding-left: 20rpx;
				display: flex;
				font-size: 32rpx;
				line-height: 52rpx;
				height: 52rpx;
				font-weight: bold;
			}
		}

		.zhinan {
			display: flex;
			font-size: 20rpx;
			font-weight: bold;
			line-height: 31rpx;
			margin: 20rpx 0;
			color: #7b7b7b;
		}

		.title {
			background: linear-gradient(18deg, #ff8f1b, #ff6400);
			line-height: 80rpx;
			font-weight: bold;
			text-align: center;
			font-size: 36rpx;
			color: #fff;
			border-radius: 20rpx 20rpx 0 0;
		}
	}

	.latest-data {
		background-color: #fff;
		color: #1d1a1a;
		padding: 20rpx;
		border-radius: 10rpx;
		margin-bottom: 20rpx;

		.title {
			font-size: 36rpx;
			font-weight: bold;
			line-height: 70rpx;
		}

		.data {
			font-size: 24rpx;
			font-weight: bold;
			line-height: 70rpx;
			margin-left: auto;
		}

		.vital-signs {
			background-color: #fff9f1;
			width: 47%;
			padding: 20rpx;
			height: 160rpx;
			margin: 10rpx auto;

			.name {
				line-height: 40rpx;
				font-size: 26rpx;
				display: flex;
			}

			.num {
				font-size: 66rpx;
				text-align: center;

				.unit {
					font-size: 20rpx;
					color: #78787b;
				}
			}
		}

		.health-status {
			height: 160rpx;
			background: url('@/img/yangcan/plbg.png') no-repeat 100% 100%;
			display: flex;
			padding: 30rpx;
			text-align: center;
			font-weight: bold;
			border-radius: 10rpx;
			margin: 20rpx 0;
			width: 98%;

			view {
				width: 50%;
			}

			.name {
				font-size: 24rpx;
				line-height: 32rpx;
				display: block;
			}

			.jieguo {
				font-size: 36rpx;
				color: #ff781d;
				line-height: 90rpx;
				display: block;
			}
		}
	}

	.zxxy {
		background: linear-gradient(to right, #fe7312, #ffd49f);
		line-height: 68rpx;
		color: #fff;
		font-size: 36rpx;
		padding: 0 20rpx;
		display: flex;
		border: 1px solid #ffb389;
		border-radius: 10rpx;
		font-weight: bold;
		margin-top: 20rpx;

		.right {
			margin-left: auto;
			font-size: 24rpx;
			color: #ff5b2f;
			display: flex;
		}
	}

	.bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
	}

	.body {
		padding: 110rpx 28rpx 0;
		color: #040303;
		background-color: #f6f2e7;
	}

	.no-scroll {
		position: fixed;
		width: 100%;
		height: 100vh;
		/* 设置为视口高度 */
		overflow: hidden;
	}

	.mask {
		width: 100vw;
		height: 100vh;
		background: rgba(0, 0, 0, 0);
		position: absolute;
		left: 0;
		top: 0;
		z-index: 99;
	}
	.top{
		position: relative;
		z-index: 99;
	}
	.home {
		font-size: 36rpx;
		display: flex;
		line-height: 50rpx;
		position: relative;
		z-index: 99;
		font-weight: bold;

		.add {
			border-radius: 25rpx;
			background-color: #f5f5f5;
			text-align: center;
			width: 50rpx;
			margin-left: auto;
			position: relative;

			.add-list {
				width: 200rpx;
				position: absolute;
				right: 0;
				bottom: -150rpx;
				border-radius: 20rpx;
				background-color: #FFFFFF;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);

				.add-list-item {
					font-size: 30rpx;
					padding: 10rpx 0;
				}
			}
		}


	}

	.memberList {
		display: flex;
		margin: 30rpx 0 0 0;
		flex-wrap: wrap;
		position: relative;
		z-index: 1;

		.name {
			font-size: 30rpx;
			margin-top: 20rpx;
		}

		.age {
			font-size: 24rpx;
		}

		.list {
			width: 25%;
			text-align: center;
			position: relative;

			.choosebg {
				position: absolute;
				z-index: -1;
				width: 130rpx;
				height: 130rpx;
				top: -1rpx;
				margin: auto;
				display: block;
				left: calc(50% - 65rpx);
			}
		}
	}

	.remind {
		background-color: #a4eccf;
		border-radius: 30rpx;
		padding: 30rpx;
		margin-top: 20rpx;

		position: relative;
		z-index: 1;

		.riqi {
			font-size: 42rpx;
		}

		.tixing {
			display: flex;
			margin: 20rpx 0;
			font-size: 36rpx;
			line-height: 80rpx;
		}

		.info {
			font-size: 38rpx;
			line-height: 76rpx;
			border-radius: 10rpx;
			background-color: #ffe539;
			text-align: center;
			color: #2b2a2e;
		}

		.time {
			font-size: 24rpx;
			line-height: 76rpx;
			text-align: center;
		}
	}

	.taideng {
		margin-top: 20rpx;
		font-size: 36rpx;
		overflow: hidden;

		.title {
			font-size: 36rpx;
			line-height: 76rpx;
		}

		.w50 {
			float: left;
			width: 48%;

			.data {
				width: 100%;
				text-align: center;
			}
		}

		.mr4 {
			margin-right: 4%;
		}

		.info {
			margin-bottom: 10px;
			background-color: #fff;
			padding: 30rpx;
			border-radius: 30rpx;
			overflow: hidden;
			position: relative;
			font-size: 36rpx;

			.diedao {
				background-color: #f2f2f2;
				font-size: 28rpx;
				font-weight: bold;
				color: #fe2d2d;
				text-align: center;
				line-height: 80rpx;
				margin-top: 20rpx;
			}

			.state2 {
				width: 72rpx;
				height: 36rpx;
				line-height: 36rpx;
				border-radius: 6rpx;
				position: absolute;
				top: 130rpx;
				right: 35rpx;
				font-size: 24rpx;
				color: #fff;
				text-align: center;
			}

			.data {
				font-size: 82rpx;
				font-weight: bold;
				line-height: 150rpx;
				float: left;

				text:last-child {
					padding-left: 10rpx;
					font-size: 26rpx;
				}
			}

			.data2 {
				font-size: 82rpx;
				font-weight: bold;
				line-height: 110rpx;
				text-align: center;

				text {
					padding-left: 10rpx;
					font-size: 26rpx;
				}
			}

			.fanwei {
				width: 100rpx;
				text-align: center;
				float: right;
				line-height: 36rpx;
				font-size: 26rpx;

				.danwei {
					font-size: 15.4rpx;
					color: #a0a0a0;
				}
			}

			.list {
				overflow: hidden;
				border-bottom: #f7f7f8 10rpx solid;
				padding-top: 30rpx;
			}

			.list:first-child {
				padding-top: 0;
			}

			.list:last-child {
				border: none;
			}

			.pilao {
				float: left;
				width: 50%;
				text-align: center;

				.name {
					font-size: 40rpx;
					font-weight: bold;
				}

				.state {
					font-size: 45rpx;
					line-height: 100rpx;
					font-weight: bold;
					color: #bbbbbb;
				}
			}
		}
	}

	.general {
		background: linear-gradient(to top right, #ccfff6, #07eacd) !important;

		.biaoqian {
			background-color: #07eacd !important;
		}
	}

	.bad {
		background: linear-gradient(to top right, #fbf7e4, #fdd209) !important;

		.biaoqian {
			background-color: #fdd209 !important;
		}
	}

	.jianbian {
		border-radius: 50%;
		overflow: hidden;
		background: linear-gradient(to top right, #b3fde3, #66de96);
		height: 100%;
		width: 100%;
		text-align: center;
		font-size: 24rpx;
		margin: 40rpx 0rpx 0 0;

		.biaoqian {
			width: 90rpx;
			margin: auto;
			background-color: #0cd10f;
			color: #fff;
			border-radius: 6rpx;
			line-height: 40rpx;
		}

		.pingfen {
			height: 190rpx;
			width: 190rpx;
			margin: 25rpx auto;
			background-color: #fff;
			border-radius: 50%;
			padding: 20rpx;
		}
	}

	.yuan {
		height: 30rpx;
		width: 30rpx;
		border-radius: 50%;
	}

	.lv {
		background-color: #0cd10f;
		margin-right: 10rpx;
	}

	.red {
		background-color: #ff2727;
	}

	.lvcolor {
		color: #0cd10f !important;
	}

	.chengcolor {
		color: #ffa126 !important;
	}

	.zi {
		background-color: #9270ff;
		margin-right: 10rpx;
	}

	.ml10 {
		font-size: 26rpx;
		margin-top: 20rpx;
		display: flex;

		text {
			margin-right: 10rpx;
		}
	}

	.ripple {
		position: absolute;
		top: -5rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: -1;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 130rpx;
		height: 130rpx;

		view {
			position: absolute;
			background: #81d3b7;
			box-sizing: border-box;
			border-radius: 100%;
			animation: animate 1s linear infinite;
			animation-delay: calc(0.5s * var(--i));
		}
	}

	.refreshing,
	.loading {
		text-align: center;
		padding: 20px;
	}

	.no-more-data {
		text-align: center;
		padding: 20px;
		color: #999;
	}

	@keyframes animate {
		0% {
			opacity: 0;
		}

		10% {
			width: 100rpx;
			height: 100rpx;
			opacity: 0.5;
		}

		50% {
			opacity: 0.5;
		}

		100% {
			width: 160rpx;
			height: 160rpx;
			opacity: 0;
		}
	}

	.data-null {
		height: 240rpx;
		font-size: 24rpx;
		color: #ff8d28;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		border-radius: 20rpx;
	}
</style>